import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    goodsList: [],
  },
  mutations: {
    SET_GOODS_LIST(state, payload) {
      // 给每个商品添加count
      payload.forEach((item) => {
        item.foods.forEach((food) => {
          food.count = 0;
        });
      });
      state.goodsList = payload
    },
    // 对商品数量做修改
    CHANGE_FOOD_COUNT(state, payload) {
      state.goodsList.forEach(item => {
        item.foods.forEach(food => {
          // 判断是否是当前点击的商品
          if (food.id === payload.id) {
            food.count = payload.type == 'Add' ?
              ++food.count :
              (food.count > 0 ? --food.count : 0)
            // if (payload.type === 'Add') {
            //   food.count++
            // } else if (payload.type === 'Minus' && food.count > 0) {
            //   food.count--
            // }
          }
        })
      })
    }
  },
  getters: {
    shopCar(state) {
      let arr = []
      // 过滤出count不为0的商品
      state.goodsList.forEach(item => {
        item.foods.forEach(food => {
          if (food.count > 0) {
            arr.push(food)
          }
        })
      })
      // console.log(arr);
      return arr
    }
  }
})
